package cn.ibizlab.eam.core.extensions.service;

import cn.ibizlab.eam.core.eam_core.domain.EMItem;
import cn.ibizlab.eam.core.eam_core.domain.EMItemTrade;
import cn.ibizlab.eam.core.eam_core.domain.EMStock;
import cn.ibizlab.eam.core.eam_core.filter.EMStockSearchContext;
import cn.ibizlab.eam.core.eam_core.service.*;
import cn.ibizlab.eam.core.eam_core.service.impl.EMItemROutServiceImpl;
import cn.ibizlab.eam.core.util.helper.Aops;
import cn.ibizlab.eam.util.dict.StaticDict;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.eam.core.eam_core.domain.EMItemROut;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

import java.util.List;

import static java.math.RoundingMode.HALF_UP;


/**
 * 实体[退货单] 自定义服务对象
 */
@Slf4j
@Primary
@Service("EMItemROutExService")
public class EMItemROutExService extends EMItemROutServiceImpl {

    @Autowired
    private IEMItemTradeService iemItemTradeService;

    @Autowired
    private IEMStockService iemStockService;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Confirm]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public EMItemROut confirm(EMItemROut et) {
        et = this.get(et.getEmitemroutid());
        if (et == null){
            throw new RuntimeException("出库单不存在，无法执行操作");
        }
        EMItemTrade emItemTrade = iemItemTradeService.get(et.getEmitemroutid());
        issueOutPuse(et,emItemTrade);
        // 流程步骤WFSTEP置空，
        et.setWfstep(null);
        // 领料单状态PUSESTATE变为“已发料”20，
        et.setTradestate(StaticDict.EMPUSESTATE.ITEM_20.getValue());
        et.setWfstate(Integer.parseInt(StaticDict.WFStates.ITEM_2.getValue()));
        Aops.getSelf(this).update(et);

        emItemTrade.setTradestate(Integer.parseInt(StaticDict.EMTRADESTATE.ITEM_20.getValue()));
        iemItemTradeService.update(emItemTrade);
        return super.confirm(et);
    }

    /**
     * 确认发料的行为，比较并修改库存、产品明细对应的信息
     */
    public void issueOutPuse(EMItemROut et, EMItemTrade emItemTrade){

        //-------------初始化单据参数
        String varOrgid = et.getOrgid();
        String varItemId = emItemTrade.getItemid();
        Double varAmount = emItemTrade.getAmount();
        Double varPsum = emItemTrade.getPsum();
        String varBatcode = emItemTrade.getBatcode();
        String varStoreId = emItemTrade.getStoreid();
        String varStorepartId = emItemTrade.getStorepartid();
        String varexOrgid = emItemTrade.getOrgid();
        Double varChangeAmount=null;

        //修改总金额
        //领料表
        et.setAmount(NumberUtils.toScaledBigDecimal(et.getPrice() * et.getPsum(), 2, HALF_UP).doubleValue());
        //物品交易表
        emItemTrade.setAmount(NumberUtils.toScaledBigDecimal(et.getPrice() * et.getPsum(), 2, HALF_UP).doubleValue());

        if (emItemTrade == null){
            throw new RuntimeException("未找到已确认的收支单据，无法完成操作");
        }
        //如果组织为空，默认是上海港
        if (varOrgid==null){
            emItemTrade.setOrgid(StaticDict.PFCL_ORG.TIP.getValue());
        }
        //批次为空，默认是NA
        if (varBatcode==null){
            emItemTrade.setBatcode("NA");
        }

        //----------- 初始化物品参数


        EMItem emItem = emitemService.get(et.getItemid());
        if (emItem == null){
            throw new RuntimeException("未找到已确认的物品信息，无法完成操作");
        }
        //库存量
        Double varItemcnt = emItem.getStocksum();
        //库存金额
        Double varItemAmount = emItem.getAmount();
        //平均价
        Double varItemPrice = emItem.getPrice();

        //初始化，如果库存和库存金额为空，默认为0
        if (varItemcnt==null){
            emItem.setStocksum(0.0);
        }
        if (varItemAmount==null){
            emItem.setAmount(0.0);
        }

        //--------------变更物品均价，总库存，总库存金额
        //varPsum实领数
        varItemcnt -= varPsum;
        if (varItemcnt<0){
            throw new RuntimeException("物品数量不够，无法完成操作");
        }
        if (varItemcnt == 0){
            varChangeAmount = varItemAmount;
        }
        //varAmount物品交易总金额
        varItemAmount -= varAmount;

        if (varItemcnt == null){
            varItemAmount = 0.0;
        }else{
            varItemPrice = NumberUtils.toScaledBigDecimal(varItemAmount/varItemcnt, 2, HALF_UP).doubleValue();
        }
        if (varItemcnt<0){
            throw new RuntimeException("物品总库存不够，无法完成操作");
        }

        //--------------初始化库存明细参数
        EMStockSearchContext ctx = new EMStockSearchContext();
        ctx.setN_itemid_eq(varItemId);
        ctx.setN_storeid_eq(varStoreId);
        ctx.setN_storepartid_eq(varStorepartId);
        ctx.setSize(1);
        List<EMStock> emStocks = iemStockService.searchDefault(ctx).getContent();
        EMStock emStock = emStocks.get(0);
        //库存数量
        Double varStockcnt = emStock.getStockcnt();

        //--------------变更库存明细总库存
        varStockcnt-=varPsum;
        if (varStockcnt<0){
            throw new RuntimeException("当前仓库物品库存不够，无法完成操作");
        }

        //修改库存数量
        emStock.setStockcnt(varStockcnt);
        emStock.setUpdateman(et.getUpdateman());
        iemStockService.update(emStock);

        //----------------库存为0 删除库存记录
        if (varStockcnt==0){
            iemStockService.remove(emStock.getEmstockid());
        }

        //----------------出空原则，更新出库金额
        //varStockcnt 库存量
        if (varStockcnt==0){
            emItemTrade.setAmount(varChangeAmount);
            iemItemTradeService.update(emItemTrade);
            et.setAmount(varChangeAmount);
            Aops.getSelf(this).update(et);
        } else{
            varStockcnt=varPsum;
            if (varStockcnt<0){
                throw new RuntimeException("当前仓库物品库存不够，无法完成操作");
            }
        }

        EMStock stock = new EMStock();
        stock.setBatcode(varBatcode);
        stock.setEnable(1);
        stock.setItemid(varItemId);
        stock.setOrgid(varexOrgid);
        stock.setStoreid(varStoreId);
        stock.setStorepartid(varStorepartId);
        stock.setStockcnt(emStock.getStockcnt());
        iemStockService.create(stock);

        //---------------初始化物品参数  税费
        double varShfamount = emItemTrade.getShf() != null ? emItemTrade.getShf() : 0;
        double varShfsum = emItemTrade.getPsum() != null ? emItemTrade.getPsum() : 0;
        double varShfprice=0;
        if (varShfsum>0){
            varShfprice= Math.round(varShfamount / varShfsum);
        }
        //------------变更物品均价，总库存，总库存金额

        emItem.setStocksum(varItemcnt);
        emItem.setPrice(varItemPrice);
        emItem.setAmount(varItemAmount);
        emItem.setStoreid(varStoreId);
        emItem.setStorepartid(varStorepartId);
        emItem.setShfprice(varShfprice);
        emitemService.update(emItem);

    }

}

